package com.xiyin.poi.service.impl;

import com.deepoove.poi.XWPFTemplate;
import com.xiyin.poi.service.WordExportService;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Service
public class WordExportServiceImpl implements WordExportService {

    public void exportWord(String outputFilePath, Map<String, Object> data) throws IOException {
        // 加载模板
        ClassPathResource templateFile = new ClassPathResource("template/demo1.docx");
        File tplFile = templateFile.getFile().getAbsoluteFile();

        // 创建数据模型
        if (data == null) {
            data = new HashMap<>();
        }
        data.put("title", "动态标题");
        data.put("content", "这是动态内容"); // 根据实际业务场景填充数据

        // 使用数据填充模板并生成Word文档
        XWPFTemplate template = XWPFTemplate.compile(tplFile).render(data);

        // 输出到指定文件路径
        File outputFile = new File(outputFilePath);
        try (OutputStream outputStream = new FileOutputStream(outputFile)) {
            template.write(outputStream);
        } finally {
            template.close();
        }
    }
}
